package org.example.websocket;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

/** 使用Netty实现的websocket服务器
 * @author Cary
 * @version 1.0
 */
public class WebSocketServer {
    private final int port;

    /** 表示WebSocket服务器监听的端口号
     * @param port
     * @return: null
     */
    public WebSocketServer(int port) {
        this.port = port;
    }

    /** 实现WebSocket服务器的启动过程
     * @throws Exception
     */
    public void run() throws Exception {
        // 创建两个事件循环组，分别用于处理客户端连接请求和数据读写
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 创建 ServerBootstrap 对象
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 添加解码器和编码器
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new HttpObjectAggregator(65536));
                            pipeline.addLast(new ChunkedWriteHandler());
                            // 添加自定义的处理器
                            pipeline.addLast(new WebSocketServerHandler());
                        }
                    });
            // 绑定端口并启动服务器
            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println("WebSocket server started on port " + port + ".");

            // 等待服务器关闭
            future.channel().closeFuture().sync();
        } finally {
            // 关闭事件循环组
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
    public static void main(String[] args) throws Exception {
        int port = 4005;
        new WebSocketServer(port).run();
    }
}
